<?php

class Uuch_Util {

    const DEFAULT_KEY = "ASWDDDJ";
    const COOKIE_NAME_RECOMMENDER = '_rmuser';

    /**
     * 加密字符串
     * 
     * @param string $string 被加密的字符串
     * @return string
     */
    static public function encryptString($string) {
        if ($string == '' && $string == null)
            return null;
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $encryptString = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::DEFAULT_KEY, strtolower($string), MCRYPT_MODE_ECB, $iv));
        return $encryptString;
    }

    /**
     * 估算纸箱重量
     * @param int $weight
     */
    public static function getPackage($weight) {
        if ($weight < 2000) {
            return 200;
        } else if ($weight < 5000) {
            return 500;
        } else if ($weight < 10000) {
            return 1000;
        } else {
            return 2000;
        }
    }

    /**
     * 解密字符串
     * 
     * @param string $string
     * @return string
     */
    public static function decryptString($string) {
        if ($string == '' && $string == null)
            return null;
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decryptString = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::DEFAULT_KEY, base64_decode($string), MCRYPT_MODE_ECB, $iv));
        return $decryptString;
    }

    public static function getUserName() {
        $username = false;
        if (isset($_COOKIE['__xxadnnx'])) {
            $username = Uuch_Util::decryptString($_COOKIE['__xxadnnx']);
        }
        if ($username) {
            $result = Application_Model_adminuser::byloginname($username);
            return $result->nikename;
        } else {
            return "Admin";
        }
    }

    public static function getUserId() {
        $username = false;
        if (isset($_COOKIE['__xxadnnx'])) {
            $username = Uuch_Util::decryptString($_COOKIE['__xxadnnx']);
        }
        if ($username) {
            $result = Application_Model_adminuser::byloginname($username);
            return $result->id;
        } else {
            return "Admin";
        }
    }

    public static function getRoleId() {
        $username = false;
        if (isset($_COOKIE['__xxadnnx'])) {
            $username = Uuch_Util::decryptString($_COOKIE['__xxadnnx']);
        }
        if ($username) {
            $result = Application_Model_adminuser::byloginname($username);
            return $result->roleid;
        } else {
            return ;
        }
    }

    public static function getUserNikeName() {
        $username = false;
        if (isset($_COOKIE['__xxadnnx'])) {
            $username = Uuch_Util::decryptString($_COOKIE['__xxadnnx']);
        }
        if ($username) {
            $result = Application_Model_adminuser::byloginname($username);
            return $result->nikename;
        }
        return "Admin";
    }
    
    public static function getActivityId() {
        $activityCode = false;
        if (isset($_COOKIE['activityCode'])) {
            $activityCode = Uuch_Util::decryptString($_COOKIE['activityCode']);
        }
        if($activityCode) {
            $activity = Application_Model_Generalize::getItemByNo($activityCode);
            return $activity->Id;
        }
        return $activityCode;
    }
    
    /**
     *  活动判断
     */
    public static function AnalysisActivity($receiveId,$receiveType) {
        $generalizeId = self::getActivityId();
        if($generalizeId) {
            $generalizeItem = Application_Model_Generalize::load($generalizeId);
            if($generalizeItem && !$generalizeItem->getJudgeIfEffective()) {
                Application_Model_GeneralizeParticipate::addParticipate($receiveId, $receiveType, $generalizeItem->No);
            }
        }
        return true;
    }

    public static function getUserGradeByUserId($userId) {
        $result = Application_Model_UserAccount::load($userId);
        return $result->UserGrade;
    }

    public static function getBacklogNum() {
        $num = Application_Model_TodoTask::getCountBySolve(Uuch_Util::getUserNikeName());
        return $num;
    }

    public static function getOutFin() {
        $orderSearch = new Application_Model_Filter_OrderSearch();
        $orderSearch->myorder = Uuch_Util::getUserNikeName();
        $orderSearch->status = Application_Model_Order::STATUS_OUTTIME_FIN; 
        $orderSearch->quickType = "finStatus";
        $num = Application_Model_Order::countorder($orderSearch);
        return $num;
    }

    /**
     * 转换成36进制，字母加数字的短
     */
    public static function getShortNum1($num, $length) {
        $base = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $num = intval($num);
        $str = "";
        while ($num > 0) {
            $cur = $num % strlen($base);

            $str = substr($base, $cur, 1) . $str;
            $num = floor($num / strlen($base));
        }
        if (strlen($str) < $length) {
            $str = str_pad($str, $length, "0", STR_PAD_LEFT);
            ;
        }

        return 'P' . $str;
    }

    /**
     * 转换成36进制，字母加数字的短
     */
    public static function getShortNum($num, $length) {
        $str = Uuch_Util::base10to33($num);
        if (strlen($str) < $length) {
            $str = str_pad($str, $length, "0", STR_PAD_LEFT);
            ;
        }
        return 'P' . $str;
    }

    public static function getAvatarFile($uid, $filename) {
        if ($filename) {
            return '/data/avatar/00.png';
        } else
            return '/data/avatar/00.png';
    }

    /*
     * 获取超时费用
     */

    public static function getTimeout($inStoreTime) {

        return 33;
    }

    public static function getDiffTime($oldTime) {
        $result = '';
        $startdate = strtotime($oldTime);
        $diffTime = round((time() - $startdate) / 60);

        if ($diffTime > (1440)) {
            $day = (int) ($diffTime / 1440);
            $diffTime = $diffTime - ($day * 1440);
            $result = $result . $day . '天';
        }

        if ($diffTime > (60) && $result == '') {
            $hour = (int) ($diffTime / 60);
            $diffTime = $diffTime - ($hour * 60);
            $result = $result . $hour . '小时';
        }

        if (!$day && !$hour && $diffTime < 10 && $result == '')
            return '刚刚';
        else if ($result == '')
            return $result . $diffTime . '分钟';
        else
            return $result;
    }

    public static function getShortString($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
        if (function_exists("mb_substr")) {
            if (mb_strlen($str, $charset) <= $length)
                return $str;
            $slice = mb_substr($str, $start, $length, $charset);
        }
        else {
            $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            if (count($match[0]) <= $length)
                return $str;
            $slice = join("", array_slice($match[0], $start, $length));
        }
        if ($suffix)
            return $slice . "…";
        return $slice;
    }

    public static function repalceName($name) {
        return $name;
    }

    /*
     * 获取运单号
     */

    public static function getWayCode() {
        $t = time();
        return substr(date('Ymd', $t), 2, 6) . Uuch_Util::base10to33($t);
    }

    /**
     * 返回订单号
     */
    public static function getVisitingNumber($userId) {
        return "Q" . substr(date('Ymd', time()), 2, 6) . Uuch_Util::base10to33((substr(time(), 5) . $userId));
    }

    /*
     * 10进制转33进制
     */

    public static function base10to33($dec) {
        $base = '0123456789ABCDEFGHIJKMNPQRSTUVWXY';
        $result = '';

        do {
            $result = $base[$dec % 33] . $result;
            $dec = intval($dec / 33);
        } while ($dec != 0);

        return $result;
    }

    /*
     * 33进制转10进制
     */

    public static function base33to10($sixty_four) {
        $base_map = array(
            '0' => 0,
            '1' => 1,
            '2' => 2,
            '3' => 3,
            '4' => 4,
            '5' => 5,
            '6' => 6,
            '7' => 7,
            '8' => 8,
            '9' => 9,
            'A' => 10,
            'B' => 11,
            'C' => 12,
            'D' => 13,
            'E' => 14,
            'F' => 15,
            'G' => 16,
            'H' => 17,
            'I' => 18,
            'J' => 19,
            'K' => 20,
            //'L' => 21,  
            'M' => 21,
            'N' => 22,
            //'O' => 24,  
            'P' => 23,
            'Q' => 24,
            'R' => 25,
            'S' => 26,
            'T' => 27,
            'U' => 28,
            'V' => 29,
            'W' => 30,
            'X' => 31,
            'Y' => 32,
                //'Z' => 35,  
        );
        $result = 0;
        $len = strlen($sixty_four);

        for ($n = 0; $n < $len; $n++) {
            $result *= 33;
            $result += $base_map[$sixty_four{$n}];
        }

        return $result;
    }

    /**
     * 创建目录，支持多级目录
     * @author wuzw
     * @param string $dir
     */
    public static function create_folders($dir) {
        return is_dir($dir) or (Uuch_Util::create_folders(dirname($dir)) and mkdir($dir, 0777));
    }

    /**
     * 查询快递状态
     * @param type $typeCom
     * @param type $typeNu
     * @return type 
     */
    public static function express($typeCom, $typeNu) {
        $AppKey = '76f5b960649455ab'; //请将XXXXXX替换成您在http://kuaidi100.com/app/reg.html申请到的KEY
        $url = 'http://api.kuaidi100.com/api?id=' . $AppKey . '&com=' . $typeCom . '&nu=' . trim($typeNu) . '&show=2&muti=1&order=desc';
//        echo $url;
        //优先使用curl模式发送数据
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $get_content = curl_exec($curl);
        curl_close($curl);
        return $get_content;
    }

    public static function expressUrl($typeCom, $typeNu) {
        $AppKey = '76f5b960649455ab'; //请将XXXXXX替换成您在http://kuaidi100.com/app/reg.html申请到的KEY
        //优先使用curl模式发送数据
        $url = "http://www.kuaidi100.com/applyurl?key=$AppKey&com=$typeCom&nu=$typeNu";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $get_content = curl_exec($curl);
        curl_close($curl);
        return $get_content;
    }

    /**
     * 快速排序
     * @param type $arr
     * @param type $sortKey
     * @return array 
     */
    public static function quickSort($arr, $sortKey) {
        $len = count($arr);
        if ($len <= 1) {
            return $arr;
        }
        $key = $arr[0]->$sortKey;
        $left_arr = array();
        $right_arr = array();

        for ($i = 1; $i < $len; $i++) {
            if ($arr[$i]->$sortKey <= $key) {
                $left_arr[] = $arr[$i];
            } else {
                $right_arr[] = $arr[$i];
            }
        }

        $left_arr = Uuch_Util::quickSort($left_arr, $sortKey);
        $right_arr = Uuch_Util::quickSort($right_arr, $sortKey);
        return array_merge($left_arr, array($arr[0]), $right_arr);
    }

    /**
     * 快速排序
     * @param type $arr
     * @param type $sortKey
     * @return array 
     */
    public static function quickArraySort($arr, $sortKey) {
        $len = count($arr);
        if ($len <= 1) {
            return $arr;
        }
        $key = $arr[0][$sortKey];
        $left_arr = array();
        $right_arr = array();

        for ($i = 1; $i < $len; $i++) {
            if ($arr[$i][$sortKey] <= $key) {
                $left_arr[] = $arr[$i];
            } else {
                $right_arr[] = $arr[$i];
            }
        }

        $left_arr = Uuch_Util::quickArraySort($left_arr, $sortKey);
        $right_arr = Uuch_Util::quickArraySort($right_arr, $sortKey);
        return array_merge($left_arr, array($arr[0]), $right_arr);
    }

    public static function convertip($ip) {
        //$ip = '58.96.180.189';
        //$ip = '61.116.81.6';
        $return = '';
        if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) {
            $iparray = explode('.', $ip);
            //echo $ip.'<br>';
            //echo $iparray[0];exit;
            if ($iparray[0] == 10 || $iparray[0] == 127 || ($iparray[0] == 192 && $iparray[1] == 168) || ($iparray[0] == 172 && ($iparray[1] >= 16 && $iparray[1] <= 31))) {
                $return = '- LAN';
            } elseif ($iparray[0] > 255 || $iparray[1] > 255 || $iparray[2] > 255 || $iparray[3] > 255) {
                $return = '- Invalid IP Address';
            } else {
                $tinyipfile = APPLICATION_PATH . '/../data/ipdata/tinyipdata1.dat';
                $fullipfile = APPLICATION_PATH . '/../data/ipdata/qqwry.dat';
                //echo $tinyipfile;
                if (@file_exists($tinyipfile)) {
                    $return = Uuch_Util::convertip_tiny($ip, $tinyipfile);
                    //echo $return;echo 'br>123';
                } elseif (@file_exists($fullipfile)) {
                    $return = Uuch_Util::convertip_full($ip, $fullipfile);
                }
            }
        }
        //var_dump($return);exit;
        return $return;
    }

    public static function convertip_tiny($ip, $ipdatafile) {
        static $fp = NULL, $offset = array(), $index = NULL;
        $ipdot = explode('.', $ip);
        $ip = pack('N', ip2long($ip));
        $ipdot[0] = (int) $ipdot[0];
        $ipdot[1] = (int) $ipdot[1];
        if ($fp === NULL && $fp = @fopen($ipdatafile, 'rb')) {
            $offset = @unpack('Nlen', @fread($fp, 4));
            $index = @fread($fp, $offset['len'] - 4);
        } elseif ($fp == FALSE) {
            return '- Invalid IP data file';
        }
        $length = $offset['len'] - 1028;
        $start = @unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);

        for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) {

            if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip) {
                $index_offset = @unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
                $index_length = @unpack('Clen', $index{$start + 7});
                break;
            }
        }

        @fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
        if ($index_length['len']) {
            return @fread($fp, $index_length['len']);
        } else {
            return 'Unknown';
        }
    }

    public static function convertip_full($ip, $ipdatafile) {
        if (!$fd = @fopen($ipdatafile, 'rb')) {
            return '- Invalid IP data file';
        }

        $ip = explode('.', $ip);
        $ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];

        if (!($DataBegin = fread($fd, 4)) || !($DataEnd = fread($fd, 4)))
            return;
        @$ipbegin = implode('', unpack('L', $DataBegin));
        if ($ipbegin < 0)
            $ipbegin += pow(2, 32);
        @$ipend = implode('', unpack('L', $DataEnd));
        if ($ipend < 0)
            $ipend += pow(2, 32);
        $ipAllNum = ($ipend - $ipbegin) / 7 + 1;

        $BeginNum = $ip2num = $ip1num = 0;
        $ipAddr1 = $ipAddr2 = '';
        $EndNum = $ipAllNum;

        while ($ip1num > $ipNum || $ip2num < $ipNum) {
            $Middle = intval(($EndNum + $BeginNum) / 2);

            fseek($fd, $ipbegin + 7 * $Middle);
            $ipData1 = fread($fd, 4);
            if (strlen($ipData1) < 4) {
                fclose($fd);
                return '- System Error';
            }
            $ip1num = implode('', unpack('L', $ipData1));
            if ($ip1num < 0)
                $ip1num += pow(2, 32);

            if ($ip1num > $ipNum) {
                $EndNum = $Middle;
                continue;
            }

            $DataSeek = fread($fd, 3);
            if (strlen($DataSeek) < 3) {
                fclose($fd);
                return '- System Error';
            }
            $DataSeek = implode('', unpack('L', $DataSeek . chr(0)));
            fseek($fd, $DataSeek);
            $ipData2 = fread($fd, 4);
            if (strlen($ipData2) < 4) {
                fclose($fd);
                return '- System Error';
            }
            $ip2num = implode('', unpack('L', $ipData2));
            if ($ip2num < 0)
                $ip2num += pow(2, 32);

            if ($ip2num < $ipNum) {
                if ($Middle == $BeginNum) {
                    fclose($fd);
                    return '- Unknown';
                }
                $BeginNum = $Middle;
            }
        }

        $ipFlag = fread($fd, 1);
        if ($ipFlag == chr(1)) {
            $ipSeek = fread($fd, 3);
            if (strlen($ipSeek) < 3) {
                fclose($fd);
                return '- System Error';
            }
            $ipSeek = implode('', unpack('L', $ipSeek . chr(0)));
            fseek($fd, $ipSeek);
            $ipFlag = fread($fd, 1);
        }

        if ($ipFlag == chr(2)) {
            $AddrSeek = fread($fd, 3);
            if (strlen($AddrSeek) < 3) {
                fclose($fd);
                return '- System Error';
            }
            $ipFlag = fread($fd, 1);
            if ($ipFlag == chr(2)) {
                $AddrSeek2 = fread($fd, 3);
                if (strlen($AddrSeek2) < 3) {
                    fclose($fd);
                    return '- System Error';
                }
                $AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
                fseek($fd, $AddrSeek2);
            } else {
                fseek($fd, -1, SEEK_CUR);
            }

            while (($char = fread($fd, 1)) != chr(0))
                $ipAddr2 .= $char;

            $AddrSeek = implode('', unpack('L', $AddrSeek . chr(0)));
            fseek($fd, $AddrSeek);

            while (($char = fread($fd, 1)) != chr(0))
                $ipAddr1 .= $char;
        } else {
            fseek($fd, -1, SEEK_CUR);
            while (($char = fread($fd, 1)) != chr(0))
                $ipAddr1 .= $char;

            $ipFlag = fread($fd, 1);
            if ($ipFlag == chr(2)) {
                $AddrSeek2 = fread($fd, 3);
                if (strlen($AddrSeek2) < 3) {
                    fclose($fd);
                    return '- System Error';
                }
                $AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
                fseek($fd, $AddrSeek2);
            } else {
                fseek($fd, -1, SEEK_CUR);
            }
            while (($char = fread($fd, 1)) != chr(0))
                $ipAddr2 .= $char;
        }
        fclose($fd);

        if (preg_match('/http/i', $ipAddr2)) {
            $ipAddr2 = '';
        }
        $ipaddr = "$ipAddr1 $ipAddr2";
        $ipaddr = preg_replace('/CZ88\.NET/is', '', $ipaddr);
        $ipaddr = preg_replace('/^\s*/is', '', $ipaddr);
        $ipaddr = preg_replace('/\s*$/is', '', $ipaddr);
        if (preg_match('/http/i', $ipaddr) || $ipaddr == '') {
            $ipaddr = '- Unknown';
        }
        return $ipaddr;
    }

    /**
     * 获得用户的真实IP地址
     *
     * @return  string
     */
    public static function real_ip() {
        $realip = NULL;

        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
                foreach ($arr AS $ip) {
                    $ip = trim($ip);

                    if ($ip != 'unknown') {
                        $realip = $ip;

                        break;
                    }
                }
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                if (isset($_SERVER['REMOTE_ADDR'])) {
                    $realip = $_SERVER['REMOTE_ADDR'];
                } else {
                    $realip = '0.0.0.0';
                }
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $realip = getenv('HTTP_CLIENT_IP');
            } else {
                $realip = getenv('REMOTE_ADDR');
            }
        }

        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        return !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    }

    const Default_City_id = 1;

    /**
     * 返回当前访问所在城市，如果没有取到数据，则默认返回美国
     * @return Application_Model_city
     */
    public static function getCurrentCity() {
        $ip = self::real_ip();
        //var_dump($ip);exit;
        $cityName = self::convertip($ip);
        $strs = preg_split("/\s+/", $cityName);
        //Application_Model_city::getByName()        
        $city = Application_Model_city::getByName(iconv('GB2312//IGNORE', 'UTF-8', $strs[0]));
        if ($city == NULL) {
            $city = Application_Model_city::load(self::Default_City_id);
        }
        return $city;
    }

    /**
     * 从指定的数组中返回满足指定条件的项
     * @param array $items 要查询的数组
     * @param function $func 条件函数
     * @return array
     */
    public static function where($items, $func) {
        $result = array();
        foreach ($items as $item) {
            if ($func($item))
                $result[] = $item;
        }
        return $result;
    }

    /**
     * 把数据用函数转换为指定的数据
     * @param type $items
     * @param type $func
     * @return type
     */
    public static function select($items, $func) {
        $result = array();
        foreach ($items as $item) {
            $result[] = $func($item);
        }
        return $result;
    }

    /**
     * 从指定的数组中返回满足指定条件的项
     * @param array $items 要查询的数组
     * @param function $func 条件函数
     * @return array
     */
    public static function first($items, $func) {
        $result = self::where($items, $func);
        if (count($result) > 0)
            return $result[0];
        else
            return null;
    }

}
